package com.tjresearch.redisdbtasktracker.runner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tjresearch.redisdbtasktracker.pojo.BuildMain;
import com.tjresearch.redisdbtasktracker.pojo.HfData;
import com.tjresearch.redisdbtasktracker.pojo.Rate;
import com.tjresearch.redisdbtasktracker.service.BuildMainService;
import com.tjresearch.redisdbtasktracker.service.JobService;
import com.tjresearch.redisdbtasktracker.utils.DateUtils;

@Component
public class RateCal {
	
	private static boolean inited = false;
	private static boolean initedAll = false;
	
	@Autowired
	private JobService jobService;
	@Autowired
	private BuildMainService buildMainService;
	/**
	 * 放入一个Map  key(原始item_id+datatype_id) value 相应得item_id(同比、环比、定基比)
	 */
	private Map<String,Integer> itemMap = new HashMap<String,Integer>();
	private Map<String, HfData> map = new HashMap<String, HfData>();
	/**
	 * 获取所有原始数据的itemId
	 * @return
	 */
	public Map<String,Integer> getItemMap()
	{
		if(!inited)
		{
			List<Integer> itemIdList = jobService.findAllSourceItemId();//所有原始数据的itemId
			for(int i  = 4 ;i <= 6 ;i++){//dataType
				for (Integer souItemId : itemIdList) {
					itemMap.put(""+souItemId+"_"+i,jobService.findRateIdByIdType(souItemId,i));
				}
				
			}
			inited = true;
		}
		return itemMap;
	}
	/**
	 * 查询daily表中的所有数据
	 * @return 含有所有数据的map key是item_id+hdate组成的字符串，value是每一行的值(hfdata)
	 */
	public Map<String, HfData> getAllMap(){
		if(!initedAll){
			map = jobService.findAllDataFinal();
			initedAll = true;
		}
		return map;
	}
	
	
	// 计算全量同比,并且放入数据库
	public void yoyAll() {
		map= getAllMap();
		itemMap = getItemMap();
		List<Rate> aRateList = new ArrayList<Rate>();
		for (Map.Entry<String, HfData> entry : map.entrySet()) {
			// 获取当前数据的itemId和时间
			Date date = entry.getValue().getHdate();
			date = DateUtils.lastOneYear(date);// 获取上一年的时间
			String key = "" + entry.getValue().getItem_id()+"_" + date.getTime();
			HfData data = map.get(key);// 上一年的数据

			if (data != null) {
				double s_result = 0;// 同比
				double nowValue = Double.parseDouble(entry.getValue().getValue());
				double lastValue = Double.parseDouble(data.getValue());
				if (lastValue != 0) {
					s_result = (nowValue - lastValue) / lastValue;
					try{
						
						Rate rate = new Rate();
						rate.setItem_id(itemMap.get(""+entry.getValue().getItem_id()+"_"+4));
						rate.setValue(s_result*100 + "");
						rate.setHdate(entry.getValue().getHdate());
						rate.setLast_update_time(entry.getValue().getTimestamp());
						aRateList.add(rate);
					}catch(Exception e){
						
					}
					if(aRateList.size()>10000)
					{
						jobService.batchInsertSRate(aRateList);
						System.out.println("yoy "+aRateList.size());
						aRateList.clear();
					}
					//jobService.insertSRate(rate);
				}
			}

		}
		if(aRateList.size()>0)
		{
			jobService.batchInsertSRate(aRateList);
			System.out.println("yoy "+aRateList.size());
		}
		
		

	}

	// 同比增量计算
	public void yoyIncremental(HfData hfData) {
		// (今年-去年)/去年
		itemMap = getItemMap();
		Date date = hfData.getHdate();
		date = DateUtils.lastOneYear(date);// 获取上一年的时间
		HfData lastData = jobService.getDataByItemAndDate(hfData.getItem_id(), date);//去年此时的数据
		if (lastData != null) {
			double s_result = 0;// 同比
			double nowValue = Double.parseDouble(hfData.getValue());
			double lastValue = Double.parseDouble(lastData.getValue());
			if (lastValue != 0) {
				s_result = (nowValue - lastValue) / lastValue;
				Rate rate = new Rate();
				rate.setItem_id(itemMap.get(""+hfData.getItem_id()+"_"+4));
				rate.setValue(s_result*100 + "");
				rate.setHdate(hfData.getHdate());
				rate.setLast_update_time(hfData.getTimestamp());
				jobService.insertSRate(rate);
			}
		}

	}
	/**
	 * 环比全量计算
	 */
	public void momAll() {
		itemMap = getItemMap();
		map= getAllMap();
		List<Rate> aRateList = new ArrayList<Rate>();
		for (Map.Entry<String, HfData> entry : map.entrySet()) {
			Date nowDate = entry.getValue().getHdate();
			int itemId = entry.getValue().getItem_id();
			double nowAve = CalculateUtils.calAve(nowDate, map, itemId);
			String key = "" + entry.getValue().getItem_id() +"_"+ DateUtils.getDayBefore(nowDate, 60).getTime();
			// 60天之前有数据
			if (map.get(key) != null) {
				double lastMonthAve = CalculateUtils.calAve(DateUtils.getDayBefore(nowDate, 30), map, itemId);// 30天前的平均
				double r_result = 0;
				if (lastMonthAve != 0) {
					r_result = (nowAve - lastMonthAve) / lastMonthAve;
					try{
						
						Rate rate = new Rate();
						rate.setItem_id(itemMap.get(""+entry.getValue().getItem_id()+"_"+5));
						rate.setValue(r_result*100 + "");
						rate.setHdate(entry.getValue().getHdate());
						rate.setLast_update_time(entry.getValue().getTimestamp());
						aRateList.add(rate);
					}catch(Exception e){
						
					}
					
					
					if(aRateList.size()>10000)
					{
						jobService.batchInsertSRate(aRateList);
						System.out.println("mom "+aRateList.size());
						aRateList.clear();
					}
					
					//jobService.insertRrate(rate);
				}
			}
		}
		if(aRateList.size()>0)
		{
			jobService.batchInsertSRate(aRateList);
			System.out.println("mom "+aRateList.size());
		}
		System.out.println("环比success");

	}

	/**
	 *  环比增量计算
	 * @param hfData 当前插入的数据
	 */
	
	public void momIncremental(HfData hfData) {
		itemMap = getItemMap();
		Date nowDate = hfData.getHdate();
		double nowAve = CalculateUtils.CalAddAve(hfData.getItem_id(), hfData.getHdate(),jobService);
		// String key =
		// ""+entry.getValue().getItem_id()+DateUtils.everyDayTime(nowDate,
		// 60).getTime();
		HfData twoMonthData = jobService.getDataByItemAndDate(hfData.getItem_id(), DateUtils.getDayBefore(nowDate, 60));
		// 60天之前有数据
		if (twoMonthData != null && twoMonthData.getValue() != null && !"".equals(twoMonthData.getValue())) {
			double lastMonthAve = CalculateUtils.CalAddAve(hfData.getItem_id(),
					DateUtils.getDayBefore(nowDate, 30),jobService);// 30天前的平均
			double r_result = 0;
			if (lastMonthAve != 0) {
				r_result = (nowAve - lastMonthAve) / lastMonthAve;
				Rate rate = new Rate();
				rate.setItem_id(itemMap.get(""+hfData.getItem_id()+"_"+5));
				rate.setValue(r_result*100 + "");
				rate.setHdate(hfData.getHdate());
				rate.setLast_update_time(hfData.getTimestamp());
				jobService.insertRrate(rate);
			}
		}

	}
	/**
	 * 定基比全量计算
	 */
	public void pobAll() {
		itemMap = getItemMap();
		map= getAllMap();
		List<Rate> aRateList = new ArrayList<Rate>();
		// 定基比
		// double valueStan = dataService.findByItemIdDate(itemId, hdate)
		for (Map.Entry<String, HfData> entry : map.entrySet()) {
			// 获取当前数据的itemId和时间
			String keyStan = "" + entry.getValue().getItem_id()+"_" + DateUtils.anyDayTimeStamp("2016-12-31");
			HfData ppx = map.get(keyStan);
			if(ppx==null)
			{
				
				continue;
			}
			String qqq = ppx.getValue();
			if(qqq==null)
			{
				
				continue;
			}
			double valueStan = Double.parseDouble(qqq);// 基准位置的数据
			double nowValue = Double.parseDouble(entry.getValue().getValue());// 现在的值
			Rate rate = new Rate();
			try{
				rate.setItem_id(itemMap.get(""+entry.getValue().getItem_id()+"_"+6));
				rate.setHdate(entry.getValue().getHdate());
				rate.setRemark(entry.getValue().getRemark());
				rate.setLast_update_time(entry.getValue().getTimestamp());
				
			}catch(Exception e){
				
			}
			if (valueStan != 0) {
				rate.setValue((nowValue / valueStan) * 100 + "");
				
				aRateList.add(rate);
				if(aRateList.size()>10000)
				{
					jobService.batchInsertSRate(aRateList);
					System.out.println("pob "+aRateList.size());
					aRateList.clear();
				}
				
				//jobService.insertFRate(rate);
			}

		}
		if(aRateList.size()>0)
		{
			jobService.batchInsertSRate(aRateList);
			System.out.println("pob "+aRateList.size());
		}
		System.out.println("定基比success");
	}
	/**
	 * 定基比增量计算
	 * @param hfData 当前插入的数据
	 */
	public void pobIncremental(HfData hfData) {
		itemMap = getItemMap();
		HfData stanData = jobService.getDataByItemAndDate(hfData.getItem_id(),
				new Date(DateUtils.anyDayTimeStamp("2016-12-31")));
		double valueStan = Double.parseDouble(stanData.getValue());
		double nowValue = Double.parseDouble(hfData.getValue());// 现在的值
		Rate rate = new Rate();
		rate.setItem_id(itemMap.get(""+hfData.getItem_id()+"_"+6));
		rate.setHdate(hfData.getHdate());
		rate.setRemark(hfData.getRemark());
		rate.setLast_update_time(hfData.getTimestamp());
		if (valueStan != 0) {
			rate.setValue((nowValue / valueStan) * 100 + "");
			jobService.insertFRate(rate);
		}

	}
	
	public void v7Function1InitDailyData()
	{
		jobService.v7Function1InitDailyData();
	}
	
	public void v7Function2InitDailyData()
	{
		jobService.v7Function2InitDailyData();
	}
	public void calCulateV7Function1() {
		int id=826;
		List<HfData> datas = jobService.findDataByDataId(id);
		List<HfData> newDatas = new ArrayList<HfData>();
		for(int i=29;i<datas.size();i++)
		{
			double sum=0;
			for(int j=i;j>i-30;j--)
			{
				HfData data = datas.get(j);
				Double v = Double.parseDouble(data.getValue());
				sum=sum+v;
			}
			double ppi = 0.42*(sum/30)+1.89;
			HfData data  = datas.get(i);
			HfData newData = data.clone();
			newData.setValue(String.valueOf(ppi));
			newDatas.add(newData);
		}
		
	}
	
	public void calCulateV7Function2() {
		int id=841;
		List<HfData> datas = jobService.findDataByDataId(id);
		List<HfData> newDatas = new ArrayList<HfData>();
		for(int i=29;i<datas.size();i++)
		{
			double sum=0;
			for(int j=i;j>i-30;j--)
			{
				HfData data = datas.get(j);
				Double v = Double.parseDouble(data.getValue());
				sum=sum+v;
			}
			double ppi = 0.52*(sum/30)-2.06;
			HfData data  = datas.get(i);
			HfData newData = data.clone();
			newData.setValue(String.valueOf(ppi));
			newDatas.add(newData);
		}
		
	}
	//使用httpclient跨域请求生成图片
	public void httpClientGenpic(){

		 CloseableHttpClient httpclient = HttpClients.createDefault();  
	     try {  
	         // 创建httpget.    
	         HttpGet httpget = new HttpGet("http://localhost:8093/genpic/drawTimeCharts");  
	         System.out.println("executing request " + httpget.getURI());  
	         // 执行get请求.    
	         CloseableHttpResponse response = httpclient.execute(httpget);  
	         try {  
	             // 获取响应实体    
	             HttpEntity entity = response.getEntity();  
	             System.out.println("--------------------------------------");  
	             // 打印响应状态    
	             System.out.println(response.getStatusLine());  
	             if (entity != null) {  
	                 // 打印响应内容长度    
	                 System.out.println("Response content length: " + entity.getContentLength());  
	                 // 打印响应内容    
	                 System.out.println("Response content: " + EntityUtils.toString(entity));  
	             }  
	             System.out.println("------------------------------------");  
	         } finally {  
	             response.close();  
	         }  
	     } catch (Exception e) {  
	         
	     } finally {  
	         // 关闭连接,释放资源    
	         try {  
	             httpclient.close();  
	         } catch (IOException e) {  
	             e.printStackTrace();  
	         }  
	     }  
	
	}
	
	//1. delete build main index data in dailydata table: delete from dailydata where item id = "xxxx"
	//
	public void fetchBuildMainIndexToDailyData() {
		jobService.deleteBuildInDaily();//删除daily填充数据item_id=1175
		List<BuildMain> buildList =  buildMainService.findAllBuildMain();//查询所有的建筑指标数据
		List<HfData> aRawSeries = new ArrayList<HfData>();//导入daily数据
		for (BuildMain buildMain : buildList) {
			HfData hfData = new HfData();
			hfData.setHdate(buildMain.getBuild_date());
			hfData.setValue(buildMain.getBuild_value()+"");
			hfData.setItem_id(1175);
			hfData.setTimestamp(new Date());
			aRawSeries.add(hfData);
			
		}
		jobService.batchInsertDailyData(aRawSeries);
	}


}
